<template>
  <!-- 项目列表弹框 -->
  <m-modal
    v-model="visible"
    :width="736"
    class="v-remoteProjectList"
    mask
    :title="title"
    :showFooter="true"
    cancelText="关闭"
    okText=""
    @cancel="handleCancel"
  >
    <div>
      <div class="_content">
        <div class="_header">
          <div class="_header-title">
            <img src="statics/images/mainpage/welcomeicondx.png">
            <p>协同项目列表</p>
          </div>
          <div class="_header-des">
            通过下载并打开M-Teamwork服务器上的项目，团队成员可以进行协同建模。
          </div>
        </div>
        <div class="_con">
          <div class="_con-div">
            <div class="_title _title-sort">
              <a-radio-group v-model="radioValue" size="small" @change="getprojectsList">
                <a-radio :value="1">
                  更新时间
                </a-radio>
                <a-radio :value="0">
                  名称
                </a-radio>
              </a-radio-group>
            </div>
            <div class="_projectList">
              <div v-if="listFlag==='successHaveData'">
                <div
                  v-for="(item,index) in projectList"
                  :key="index"
                  class="g-pointer _projectList-item"
                  :class="{itemBackground:changeBackground === index}"
                  @click="projectItemClick(index,item.config.projectDescription)">
                  <div class="__left">
                    <div class="__name" :title="item.config.projectName">{{item.config.projectName}}</div>
                    <div class="__time">{{item.interval}}</div>
                  </div>
                  <div class="__center">
                    <a-spin v-if="item.loading">
                      <a-icon
                        slot="indicator"
                        type="loading"
                        style="font-size: 24px; top: 63%; left: 0;"
                        spin
                      />
                      <div style="margin-left: 28px;margin-top: 12px;color: #2695FF">
                        下载中...
                      </div>
                    </a-spin>
                  </div>
                  <div class="__right">
                    <a-button v-if="item.btnFlag===1" class="__btn" @click="downloadAction(item.config.id, item.config.projectName)">
                      <div class="icon-all icon-download"></div>
                      <div style="margin-top:2px">下载</div>
                    </a-button>
                    <a-button v-if="item.btnFlag===2" class="__btn" @click="cancelDownload(item.config.id)">
                      <div class="icon-all icon-cancel"></div>
                      <div style="margin-top:2px">取消</div>
                    </a-button>
                    <a-button v-if="item.btnFlag===3" class="__btn"  @click="openFile(item.config.id, item.path)">
                      <div class="icon-all icon-open"></div>
                      <div style="margin-top:2px">打开</div>
                    </a-button>
                  </div>
                </div>
              </div>
              <div v-if="listFlag==='successNoData'" style="text-align:center;">
                <div style="margin-top:87px;color:#000;">暂无项目</div>
                <div style="margin-top:8px;">你可以将一个本地项目发布为协同项目。</div>
              </div>
              <div v-if="listFlag==='fail'" style="text-align:center;">
                <div style="margin-top:87px;color:#000;">获取项目列表失败</div>
                <a style="margin-top:8px;" @click="getprojectsList">重新获取</a>
              </div>
              <div v-if="listFlag==='loading'" style="text-align:center;margin-top:111px;">
                <img src="statics/images/mainpage/iconcircle.svg" class="loadingImg">
              </div>
            </div>
            <div class="_title _title-des">
              <span>项目描述</span>
            </div>
            <div class="_projectDes">
              {{projectDescription}}
            </div>
          </div>
        </div>
      </div>
    </div>
  </m-modal>
</template>
<script>
import customModal from "../common/CustomModal";
import { Portal } from "src/components/common/Portal.vue";
import LocalFile from "src/util/localFile/index";
import { formatTime, getTimeDiff } from "src/util/common";
import { storage } from "src/util/common";
import { API } from "@/constants/api";

const com = {
  name: "remoteProjectList",
  components: {
    "m-modal": customModal,
  },
  data() {
    return {
      visible: false,
      title: "协同项目",
      radioValue: 1,
      listFlag: "loading",
      projectList: [],
      projectDescription: "暂无描述",
      changeBackground: undefined,
      selectPath: "",
    };
  },

  computed: {},
  watch: {},
  mounted() {
    this.visible = true;
    this.getprojectsList();
  },
  beforeCreate() {},
  beforeDestroy() {},
  methods: {
    handleOk(res) {
      this.visible = false;
      this.$emit("sure", res);
    },
    handleCancel() {
      this.visible = false;
      this.$emit("close");
    },
    //// 获取项目列表
    getprojectsList() {
      this.listFlag = "loading";
      this.$get(API.PLATFORM_SERVICE_PROJECT_LIST, { sort: this.radioValue })
        .then((res) => {
          let resData = res.data;
          if (resData.length === 0) {
            this.listFlag = "successNoData";
            return;
          }
          this.listFlag = "successHaveData";
          resData.forEach((item) => {
            let time =
							Date.now() -
							new Date(item.config.updateDate).getTime();
            if (time < 60000) {
              item.interval = `刚刚更新`;
            } else if (time > 2592000000) {
              item.interval = formatTime(
                item.config.updateDate,
                "HH:mm YYYY/MM/DD"
              );
            } else {
              item.interval = getTimeDiff(item.config.updateDate);
            }
            item.loading = false;
            item.btnFlag = 1;
            //// 根据本地存储设置为打开
            let downloadProjects =
							storage.get("downloadProjects") || [];
            if (downloadProjects.length) {
              //// const findIndex = downloadProjects.findIndex(it => it.id === item.config.id);
              //// if (findIndex === -1){
              ////   downloadProjects.splice(index, 1);
              //// }
              downloadProjects.forEach((i) => {
                if (i.id === item.config.id) {
                  item.btnFlag = 3;
                  item.path = i.path;
                }
              });
            }
          });
          this.projectList = resData;
        })
        .catch((err) => {
          this.listFlag = "fail";
        });
    },
    //// 点击下载按钮,弹出文件选择框
    downloadAction(id, name) {
      //// 如果是浏览器，直接下载
      if (!this.$globalConfig.isElectron) {
        this.downloadProjectById(id, name);
        return;
      }
      //// 如果是客户端，打开对话框
      let option = {
        title: "保存协同项目",
        defaultPath: name,
        filters: [
          {
            name: "M-Design Collaboration Project",
            extensions: ["md3t"],
          }
        ],
      };
      const selectPath = LocalFile.showSaveDialog(option);
      if (selectPath) {
        this.downloadProjectById(id, name, selectPath);
      }
    },
    //// 根据项目id下载
    downloadProjectById(id, name, selectPath) {
      let downloadProject = this.projectList.find(
        (item) => item.config.id === id
      );
      downloadProject.loading = true;
      downloadProject.btnFlag = 2;
      this.$get(API.PLATFORM_SERVICE_PROJECT_DOWNLOAD, { _id: id }, { responseType: "arraybuffer" })
        .then((res) => {
          //// console.log(deSerModel(res.data.model));
          //// download(name, res.data.model);
          LocalFile.downLoadFile({
            filename: name,
            content: res.data,
            contentType: res.headers["content-type"],
            selectPath: selectPath,
          });
          //// 下载完成--将下载按钮设置为打开
          downloadProject.btnFlag = 3;
          downloadProject.loading = false;
          downloadProject.path = selectPath;
          //// 本地存储
          const downloadProjects =
						storage.get("downloadProjects") || [];
          downloadProjects.push({ id: id, path: selectPath });
          this.$globalConfig.setDownloadProjects(downloadProjects);
        })
        .catch((err) => {
          throw err;
        });
    },
    //// 点击每一项
    projectItemClick(index, projectDescription) {
      this.changeBackground = index;
      this.projectDescription = projectDescription || "暂无描述";
    },
    //// 打开文件
    openFile(id, path) {
      //// 如果是客户端，打开文件，暂不处理浏览器
      if (this.$globalConfig.isElectron) {
        if (window.$ele.fs.existsSync(path)) {
          this.handleCancel();
        }
        LocalFile.openProject(path)
          .then((project) => {
            //// 打开项目成功，切换项目
            LocalFile.switchToProject(project);
          })
          .catch((err) => {
            //// if (err) return false;
            console.error(err);
            app.$messageBox.error({
              id: "open error",
              text: "无法在本地找到对应的协同项目。请重新下载。",
              key: "协同错误",
              duration: 10,
            });
            this.projectList.find(
              (item) => item.config.id === id
            ).btnFlag = 1;
            //// 删除本地存储的这一项
            const downloadProjects = this.$globalConfig
              .downloadProjects;
            if (downloadProjects.length > 0) {
              downloadProjects.forEach((i, index) => {
                if (i.id === id) {
                  this.$globalConfig.downloadProjects.splice(
                    index,
                    1
                  );
                  this.$globalConfig.setDownloadProjects(
                    this.$globalConfig.downloadProjects
                  );
                }
              });
            }
          });
      }
    },
    //// 取消下载
    cancelDownload(id) {
      this.projectList.find(
        (item) => item.config.id === id
      ).loading = false;
      this.projectList.find((item) => item.config.id === id).btnFlag = 1;
    },
  },
};
export default com;
export const remoteProjectListModal = new Portal(com, { single: true });
</script>
<style lang="scss" scoped>
.v-remoteProjectList {
	._content {
		._header {
			width: 734px;
			height: 96px;
			background-image: url("~statics/images/mainpage/addtitlebg.png");
			._header-title {
				padding-top: 12px;
				padding-left: 19px;
				display: flex;
				> img {
					width: 32px;
					height: 32px;
				}
				> p {
					line-height: 32px;
					margin-bottom: 0;
					font-weight: bold;
					font-size: 14px;
				}
			}
			._header-des {
				padding-left: 24px;
				height: 24px;
				line-height: 24px;
			}
		}
		._con {
			._con-div {
				width: 687px;
				height: 410px;
				margin: 18px 24px 24px 24px;
				background: #ffffff;
				border: 1px solid #d9d9d9;
				border-top: 0;
				._title {
					width: 687px;
					height: 24px;
					background: #d4ebf8;
					border-top: 1px solid #b1cee2;
					border-bottom: 1px solid #b1cee2;
					padding-left: 16px;
					margin-left: -1px;
					/deep/ .ant-radio-wrapper {
						font-size: 12px;
					}
					&._title-des {
						font-weight: 500;
						font-family: "PingFangSC-Medium, PingFang SC";
					}
				}
				._projectList {
					height: 287px;
					overflow: auto;
					._projectList-item {
						display: flex;
						height: 44px;
						padding-left: 18px;
						padding-right: 12px;
						margin: 9px 0 9px;
						.__left {
							width: 480px;
							.__name {
                width: 315px;
								height: 24px;
								line-height: 24px;
								font-size: 12px;
								font-weight: 400;
								color: #000000;
								overflow: hidden;
								text-overflow: ellipsis;
								white-space: nowrap;
								&:hover {
									color: #0f6baa;
								}
							}
							.__time {
								font-weight: 400;
								color: rgba(0, 0, 0, 0.65);
							}
						}
						.__center {
							width: 100px;
						}
						.__right {
							/deep/ .ant-btn {
								padding: 0 10px;
							}
							.__btn {
								width: 69px;
								height: 26px;
								display: flex;
                align-items: center;
								margin-top: 9px;
								background: #fff;
								border: 1px solid #d9d9d9;
								.icon-all {
									width: 16px;
									height: 24px;
									&.icon-open {
										background: url("~statics/images/mainpage/iconopen.svg")
											no-repeat center center;
									}
									&.icon-download {
										background: url("~statics/images/mainpage/iconldownload.svg")
											no-repeat center center;
									}
									&.icon-cancel {
										background: url("~statics/images/mainpage/iconcancel.svg")
											no-repeat center center;
									}
								}
							}
						}
						&:hover {
							.__left {
								.__name {
									color: #0f6baa;
								}
							}
							.__right {
								.__btn {
									color: #40a9ff;
									border: 1px solid #40a9ff;
									.icon-all {
										&.icon-open {
											background: url("~statics/images/mainpage/iconopenblue.svg")
												no-repeat center center;
										}
										&.icon-download {
											background: url("~statics/images/mainpage/iconldownloadblue.svg")
												no-repeat center center;
										}
										&.icon-cancel {
											background: url("~statics/images/mainpage/iconcancelblue.svg")
												no-repeat center center;
										}
									}
								}
							}
						}
					}
					.itemBackground {
						.__left {
							.__name {
								color: #0f6baa;
							}
						}
						.__right {
							.__btn {
								color: #40a9ff;
								border: 1px solid #40a9ff;
								.icon-all {
									&.icon-open {
										background: url("~statics/images/mainpage/iconopenblue.svg")
											no-repeat center center;
									}
									&.icon-download {
										background: url("~statics/images/mainpage/iconldownloadblue.svg")
											no-repeat center center;
									}
									&.icon-cancel {
										background: url("~statics/images/mainpage/iconcancelblue.svg")
											no-repeat center center;
									}
								}
							}
						}
					}
					.loadingImg {
						animation: loadingani 1s;
						-webkit-animation: loadingani 1s; /* Safari and Chrome */
						animation-iteration-count: infinite;
					}
					@keyframes loadingani {
						from {
							transform: rotate(0deg);
						}
						to {
							transform: rotate(360deg);
						}
					}
				}
				._projectDes {
					height: 75px;
					padding-top: 9px;
					padding-left: 17px;
				}
			}
		}
	}
}
</style>
